package li.tmi.TxBtry;


import android.appwidget.AppWidgetProvider;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.widget.RemoteViews;

public class WidgetProvider extends AppWidgetProvider {
	
	@Override
	public void onUpdate( Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds )
	{
		for (int i=0; i<appWidgetIds.length; i++) {
			Intent objServiceIntent = new Intent(context, UpdateService.class);
			objServiceIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetIds[i]);
			context.startService(objServiceIntent);
	    }
	}
	
	@Override
    public void onDeleted(Context context, int[] appWidgetIds) {
    	
        // When the user deletes the widget, delete the preference associated with it.
    	TxPref txpref = new TxPref(TxPref.PREFS_NAME_TXBTRY);
        final int N = appWidgetIds.length;
        for (int i=0; i<N; i++) {
            txpref.deletePreAndId(context, appWidgetIds[i]);
        }
    }
	
	public static void updateWidget(Context context, AppWidgetManager appWidgetManager, int id) {
		System.out.println("updating widget");
		TxPref txpref = new TxPref(TxPref.PREFS_NAME_TXBTRY);
        
		//getting the Widget views
		RemoteViews views = null;   
		views = new RemoteViews(context.getPackageName(), R.layout.widget);
		
		System.out.println(txpref.getBtryMisc(context, id, TxPref.BTRYRTIME));
		if(txpref.getBtryMisc(context, id, TxPref.BTRYRTIME) != null) {
			long time = Long.valueOf(txpref.getBtryMisc(context, id, TxPref.BTRYRTIME));
			String current = txpref.getBtryMisc(context, id, TxPref.BTRYCLEVEL);
			String isPlugged = txpref.getBtryMisc(context, id, TxPref.BTRYPLUG);
			TxBtryTime txbtr = new TxBtryTime(time);
			System.out.println("isPlugged : "+isPlugged);
			if(isPlugged == "true") {
				views.setTextViewText(R.id.bigleft, current);
				views.setTextViewText(R.id.smalltopright, "chrgn");
				views.setTextViewText(R.id.smallbottomright, ""+txbtr.getHours()+":"+txbtr.getMinutes());
			}else {
				views.setTextViewText(R.id.bigleft, current);
				views.setTextViewText(R.id.smalltopright, txbtr.getHours()+" hrs");
				views.setTextViewText(R.id.smallbottomright, txbtr.getMinutes()+" mins");
			}			
		}else {
			views.setTextViewText(R.id.bigleft, "50");
			views.setTextViewText(R.id.smalltopright, "unknwn");
			views.setTextViewText(R.id.smallbottomright, "unknwn");
		}
		//stopping the service since i got the update alrdy
		//Intent service = new Intent(context, UpdateService.class);
		//context.stopService(service);
		//updating the widget via the widget manager
		appWidgetManager.updateAppWidget(id, views);
	}
}
